<?php
declare (strict_types=1);

namespace app\common\model;

use app\admin\model\BaseModel;

class Attachment extends BaseModel
{
    //当前模型对应的数据表名称
    protected $name = 'attachment';

    protected $append = [
        //'url',
    ];

    public function getList($filter = []): array
    {
        $where = function ($query) use ($filter) {
            if (isset($filter['filename'])) {
                $query->where('filename', 'like', '%' . $filter['filename'] . '%');
            }
            if (isset($filter['suffix'])) {
                $query->where('suffix', 'like', '%' . $filter['suffix'] . '%');
            }
            if (isset($filter['storage'])) {
                $query->where('storage', '=', $filter['storage']);
            }
            if (isset($filter['time'])) {
                $startTime = date('Y-m-d', strtotime($filter['time'][0])) . ' 00:00:00';
                $endTime = date('Y-m-d', strtotime($filter['time'][1])) . ' 23:59:59';
                $query->whereTime('createtime', 'between', [$startTime, $endTime]);
            }
        };
        $order = ['createtime' => 'desc', 'id' => 'desc'];
        return self::getPageList($where, $order);
    }

    public function getUrlAttr($value, $data)
    {
        if ($data['domain']) {
            return $data['domain'] . '/' . $data['path'];
        } else {
            return request()->domain() . $data['path'];
        }
    }

    public function getFilesizeAttr($value, $data)
    {
        return format_size($value);
    }

}